<template>
	<view class="content device-add-tab">
		<!-- 页面标题 -->
		<view class="page-title">
			<text>添加设备</text>
		</view>

		<!-- 直接嵌入设备添加页面内容 -->
		<view class="scan-section">
			<view class="scan-card">
				<view class="scan-frame">
					<image @click="saomafunc()" src="/static/a1.png" mode="aspectFit" class="barcode-image"></image>
				</view>
				<text class="card-label">基本信息</text>
			</view>
		</view>

		<view class="form-section">
			<view class="form-item">
				<text class="label required">设备序列号：</text>
				<input type="text" class="input" placeholder="请输入序列号" placeholder-class="placeholder"
					v-model="deviceData.serialNumber" />
				<view class="search-icon">
					<image @click="searchfunc()" src="/static/a2.png" mode="aspectFit"></image>
				</view>
			</view>

			<view class="form-item">
				<text class="label">设备名称：</text>
				<input type="text" class="input" disabled placeholder="根据序列号获取" placeholder-class="placeholder"
					v-model="deviceData.deviceName" />
			</view>

			<view class="form-item">
				<text class="label">设备型号：</text>
				<input type="text" class="input" disabled placeholder="根据序列号获取" placeholder-class="placeholder"
					v-model="deviceData.deviceModel" />
			</view>

			<view class="form-item">
				<text class="label">设备图片：</text>
				<input type="text" class="input" disabled placeholder="根据序列号获取" placeholder-class="placeholder"
					v-model="deviceData.deviceImage" />
			</view>

			<view class="form-item">
				<text class="label">SIM卡号：</text>
				<input type="text" class="input" disabled placeholder="根据序列号获取" placeholder-class="placeholder"
					v-model="deviceData.simCard" />
			</view>

			<view class="form-item">
				<text class="label">安装地址：</text>
				<view class="input-scroll-wrapper">
					<textarea class="input scrollable-input" placeholder="请输入设备地址" placeholder-class="placeholder"
						v-model="deviceData.installAddress"></textarea>
				</view>
				<view class="get-btn" @click="getLocation">
					<text>获取</text>
				</view>
			</view>

			<view class="form-item">
				<text class="label">上报周期(s)：</text>
				<input type="text" class="input" disabled placeholder="根据序列号获取" placeholder-class="placeholder"
					v-model="deviceData.reportCycle" />
			</view>
		</view>

		<view class="save-btn" @click="saveDevice">
			<text>保存</text>
		</view>

		<!-- 隐藏的文件输入框用于图片上传扫码 -->
		<input type="file" ref="fileInput" id="fileInputEl" accept="image/*" capture="environment"
			style="display: none;" @change="handleImageUpload" />
	</view>
</template>

<script>
	import {
		geyAdderssApi,
		savafunc,
		searchfunc
	} from '@/api/user.js'
	export default {
		name: 'AddDevice',
		data() {
			return {
				deviceData: {
					// P4F6192370920204
					serialNumber: 'P4F6192370920204',
					deviceName: '',
					deviceModel: '',
					deviceImage: '',
					simCard: '',  
					installAddress: '',
					reportCycle: '',
				}
			}
		},
		methods: {
			saveDevice() {
				savafunc(this.deviceData).then(res=>{
					if(res.success == true){
						uni.showToast({
							title: res.msg,
							icon: 'success'
						});
						// Forma más concisa de limpiar el objeto deviceData
						Object.keys(this.deviceData).forEach(key => {
							this.deviceData[key] = '';
						});
					}else{
						uni.showToast({
							title: res.msg,
							icon: 'error'
						});
					}
				})
				
				// 保存后通知父组件返回首页
				// this.$emit('saved');
			},
			
			searchfunc(){
				this.getinfo()
			},
			
			// 扫码选项菜单
			saomafunc() {
				// 直接使用内置浏览器扫码，不使用条件编译
				// 简化选项为直接从相册选择
				uni.showToast({
					title: '正在初始化扫码功能',
					icon: 'none',
					duration: 1000
				});

				setTimeout(() => {
					// 直接使用相册选择功能，更加通用
					this.chooseImage();
				}, 500);
			},

			// 从相册选择图片 - 使用更简单的实现
			chooseImage() {
				// 兼容H5和APP
				try {
					// 尝试使用uni API
					uni.chooseImage({
						count: 1,
						sizeType: ['original', 'compressed'],
						sourceType: ['album', 'camera'],
						success: (res) => {
							console.log('选择图片成功', res);
							// 模拟扫码成功
							this.processBarcodeScan('ABC123456789');
						},
						fail: (err) => {
							console.error('选择图片失败', err);
							// 如果uni API失败，尝试原生方式
							this.$nextTick(() => {
								// 直接触发隐藏的文件输入
								document.getElementById('fileInputEl').click();
							});
						}
					});
				} catch (e) {
					console.error('uni.chooseImage错误', e);
					// 如果uni API不可用，尝试原生方式
					this.$nextTick(() => {
						// 直接触发隐藏的文件输入
						document.getElementById('fileInputEl').click();
					});
				}
			},

			// 处理上传的图片
			handleImageUpload(event) {
				console.log('文件上传事件触发');
				const file = event.target.files[0];
				if (!file) {
					console.log('没有选择文件');
					return;
				}

				// 显示加载提示
				uni.showLoading({
					title: '处理中...'
				});

				// 模拟处理时间
				setTimeout(() => {
					// 模拟扫码成功
					this.processBarcodeScan('ABC123456789');
					// 隐藏加载提示
					uni.hideLoading();
					// 清空文件输入，以便下次可以选择相同的文件
					event.target.value = '';
				}, 1000);
			},

			// 处理扫码结果
			processBarcodeScan(code) {
				// 填充序列号字段
				console.log('扫码结果：', code);
				this.deviceData.serialNumber = code;
				this.getinfo()
			},
			
			getinfo(){
				searchfunc({
					serialNumber: this.deviceData.serialNumber
				}).then(res=>{
					if(res.success == true){
						uni.showToast({
							title: '查询成功',
							icon: 'success'
						});
						setTimeout(() => {
							this.deviceData.serialNumber = res.data.serialNumber
							this.deviceData.deviceName = res.data.deviceName
							this.deviceData.deviceModel = res.data.deviceModel
							this.deviceData.deviceImage = res.data.deviceImage
							this.deviceData.simCard = res.data.simCard
							this.deviceData.reportCycle = res.data.reportCycle;
							this.deviceData.installAddress = res.data.installAddress;
						}, 500); 
					}else{
						uni.showToast({
							title: '查询失败',
							icon: 'error'
						});
					}
				})
			},

			// 获取地理位置信息
			getLocation() {
				uni.showLoading({
					title: '获取位置中...'
				});
				uni.getLocation({
					type: 'wgs84',
					success: (res => {
						let objVal = {
							key: 'NSRBZ-CBUCJ-HEDFU-D3FBJ-54SX7-GMBY2',
							location: res.latitude + ',' + res.longitude,
							get_poi: 1
						} 
						geyAdderssApi(objVal).then(item => {
							if (item.status == 0) {
								this.deviceData.installAddress = item.result.address
							} else {
								uni.showToast({
									title: `${items.message}`,
									icon: 'none',
									duration: 2000
								});
							}
								uni.hideLoading()
						})
					})

				});
			},

		}
	}
</script>

<style lang="scss">
	.device-add-tab {
		padding: 0;
		background-color: #f0f0f0;
		width: 100%;
	}

	/* Page title now uses global style */

	.scan-section {
		background-color: #3373ff;
		padding: 20rpx;
		width: 100%;
		box-sizing: border-box;

		.scan-card {
			background-color: #fff;
			border-radius: 16rpx;
			padding: 40rpx 0 30rpx;
			width: 100%;
			position: relative;

			.scan-frame {
				width: 300rpx;
				height: 170rpx;
				position: relative;
				display: flex;
				justify-content: center;
				align-items: center;
				margin: 0 auto 8px;
			}

			.card-label {
				position: absolute;
				bottom: 20rpx;
				left: 30rpx;
				font-size: 26rpx;
				font-weight: bold;
				color: #333;
			}
		}
	}

	.form-section {
		background-color: #fff;
		margin: 0 24rpx;
		// width: 100%;

		.form-item {
			display: flex;
			align-items: center;
			padding: 30rpx;
			border-bottom: 1px solid #eee;
			position: relative;

			.label {
				width: 220rpx;
				font-size: 28rpx;
				color: #666;

				&.required:before {
					content: '*';
					color: red;
					margin-right: 4rpx;
				}
			}

			.input {
				flex: 1;
				height: 70rpx;
				font-size: 28rpx;
				color: #333;
			}
			
			textarea.input {
				height: auto;
				min-height: 70rpx;
				padding: 8rpx 0;
				line-height: 1.4;
			}
			
			.input-scroll-wrapper {
				flex: 1;
				overflow-x: visible;
				white-space: normal;
				
				.scrollable-input {
					width: 100%;
					white-space: normal;
					overflow-x: visible;
					text-overflow: ellipsis;
					word-break: break-all;
				}
			}

			.placeholder {
				color: #999;
			}

			.search-icon {
				width: 60rpx;
				height: 60rpx;
				display: flex;
				justify-content: center;
				align-items: center;

				image {
					width: 40rpx;
					height: 40rpx;
				}
			}

			.get-btn {
				text {
					color: #3373ff;
					font-size: 26rpx;
				}
			}
		}
	}

	.save-btn {
		// margin: 60rpx 30rpx;
		margin: 60rpx auto;
		height: 90rpx;
		background-color: #3373ff;
		border-radius: 10rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		width: calc(100% - 60rpx);
		width: 50%;

		text {
			color: #fff;
			font-size: 32rpx;
		}
	}
</style>